// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Web;
using System.Configuration;
using System.Web.SessionState;
using System.Data;
using System.Collections;
using System.Text;
using System.Xml;
using System.IO;
using System.Globalization;
using System.Data.SqlClient;

namespace InterpriseSuiteEcommerceCommon
{
	/// <summary>
	/// Summary description for Shipping.
	/// </summary>
	public class Shipping
	{

		// this MUST match the table defs in ShippingCalculation table
		public enum ShippingCalculationEnum
		{
			Unknown = 0,
			CalculateShippingByWeight = 1,
			CalculateShippingByTotal = 2,
			UseFixedPrice = 3,
			AllOrdersHaveFreeShipping = 4,
			UseFixedPercentageOfTotal = 5,
			UseIndividualItemShippingCosts = 6,
			UseRealTimeRates = 7,
			CalculateShippingByWeightAndZone = 8,
			CalculateShippingByTotalAndZone = 9
		};

		public enum FreeShippingReasonEnum
		{
			DoesNotQualify = 0,
			AllOrdersHaveFreeShipping = 1,
			AllDownloadItems = 2,
			ExceedsFreeShippingThreshold = 3,
			CustomerLevelHasFreeShipping = 4,
			CouponHasFreeShipping = 5,
			AllFreeShippingItems = 6
		};

        public Shipping() { }

        static public decimal GetVariantShippingCost(String VariantID, String ShippingMethodID)
        {
            decimal tmp = System.Decimal.Zero;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "select ShippingCost from ShippingByProduct with (NOLOCK) where VariantID=" + VariantID.ToString() + " and ShippingMethodID=" + ShippingMethodID.ToString()))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSFieldDecimal(rs, "ShippingCost");
                    }
                }
            }                    
	
            return tmp;
        }

		static public String GetFreeShippingMethodID()
		{
			String FreeShippingMethodID = AppLogic.AppConfig("ShippingMethodIDIfFreeShippingIsOn");
			if(FreeShippingMethodID == String.Empty)
			{
				// forcefully set this appconfig for the store admin:
                using (SqlConnection con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (IDataReader rs = DB.GetRSFormat(con, "select top 1 ShippingMethodID from ShippingMethod with (NOLOCK) where IsRTShipping=0 order by DisplayOrder"))
                    {
                        if (rs.Read())
                        {
                            FreeShippingMethodID = DB.RSField(rs, "ShippingMethodID");
                        }
                    }
                }
  
				if(FreeShippingMethodID == String.Empty)
				{
					throw new ArgumentException("You must set AppConfig:ShippingMethodIDIfFreeShippingIsOn to the shipping method ID to use for orders which meet free shipping threshold requirements!");
				}
				else
				{
					AppLogic.SetAppConfig(0,"ShippingMethodIDIfFreeShippingIsOn",FreeShippingMethodID.ToString());
				}
			}
			return FreeShippingMethodID;
		}
		
		static public bool MultiShipEnabled()
		{
            return AppLogic.AppConfigBool("AllowMultipleShippingAddressPerOrder");
		}
		
		static public String ZoneLookup(String zip)
		{
			zip = zip.PadLeft(5,'0');
			String Zip3 = zip.Substring(0,3);
			int Zip3Int = 0;
			try
			{
				Zip3Int = Localization.ParseUSInt(Zip3);
			}
			catch
			{
				return AppLogic.AppConfig("ZoneIDForNoMatch"); // something bad as input zip
			}
			String ZoneID = String.Empty;
            DataSet ds = DB.GetDS("select * from ShippingZone with (NOLOCK)", AppLogic.CachingOn, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
			foreach(DataRow row in ds.Tables[0].Rows)
			{
				String[] thisZipList = DB.RowField(row,"ZipCodes").Split(',');
				foreach(String s in thisZipList)
				{
					// is it a single 3 digit prefix, or a range:
					if(s.IndexOf("-") == -1)
					{
						// single item:
						int LowPrefix = 0;
						try
						{
							if(CommonLogic.IsInteger(s))
							{
								LowPrefix = Localization.ParseUSInt(s);
							}
						}
						catch {}
						if(LowPrefix == Zip3Int)
						{
							ZoneID = DB.RowField(row,"ShippingZoneID");
							break;
						}
					}
					else
					{
						// range:
						String[] s2 = s.Split('-');
						int LowPrefix = 0;
						int HighPrefix = 0;
						try
						{
							if(CommonLogic.IsInteger(s2[0]))
							{
								LowPrefix = Localization.ParseUSInt(s2[0]);
							}
							if(CommonLogic.IsInteger(s2[1]))
							{
								HighPrefix = Localization.ParseUSInt(s2[1]);
							}
						}
						catch {}
						if(LowPrefix <= Zip3Int && Zip3Int <= HighPrefix)
						{
							ZoneID = DB.RowField(row,"ShippingZoneID");
							break;
						}
					}
				}
			}
			ds.Dispose();
			if(ZoneID == String.Empty)
			{
				ZoneID = AppLogic.AppConfig("ZoneIDForNoMatch");
			}
			return ZoneID;
		}

		static public String GetShippingMethodID(String Name)
		{
			String tmp = String.Empty;
			DataSet ds = DB.GetDS("Select * from ShippingMethod with (NOLOCK) order by DisplayOrder","ShippingMethods DataSet",AppLogic.CachingOn,System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
			foreach(DataRow row in ds.Tables[0].Rows)
			{
				if(Name.ToLower() == DB.RowField(row,"Name").ToLower())
				{
					tmp = DB.RowField(row,"ShippingMethodID");
					break;
				}
			}
			ds.Dispose();
			return tmp;
		}
		
		public static String GetZoneName(String ShippingZoneID, String LocaleSetting)
		{
			String tmpS = String.Empty;
			if(ShippingZoneID != String.Empty)
			{
                using (SqlConnection con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (IDataReader rs = DB.GetRSFormat(con, "select Name from ShippingZone with (NOLOCK) where ShippingZoneID=" + ShippingZoneID.ToString()))
                    {
                        if (rs.Read())
                        {
                            tmpS = DB.RSFieldByLocale(rs, "Name", LocaleSetting);
                        }
                    }
                }
			}
			return tmpS;
		}
	
	}
}
